﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TYAJZWeb.Models;
using TYAJZWeb.Data;

using TYAJZWeb.Utils;
using Newtonsoft.Json;
using Microsoft.International.Converters.PinYinConverter;
using System.Text;


namespace TYAJZWeb.Controllers
{
    public class CompanyController : BaseController
    {
        [CookiesAuthorize]
        public ActionResult List(int page,CompanySearchModel model)
        {
            var r1 = Context.Companies.Where(t => t.IsDeleted == false);
            if (model != null)
            {
                if (!String.IsNullOrEmpty(model.Name))
                    r1 = r1.Where(t => t.Name.Contains(model.Name));

                if (!String.IsNullOrEmpty(model.Address))
                    r1 = r1.Where(t => t.Address.Contains(model.Address));

                if (!String.IsNullOrEmpty(model.Contactor))
                    r1 = r1.Where(t => t.Contactor.Contains(model.Contactor));

                if (!String.IsNullOrEmpty(model.InstallNO))
                    r1 = r1.Where(t => t.InstallCertNO.Contains(model.InstallNO));

                if (!String.IsNullOrEmpty(model.Legal))
                    r1 = r1.Where(t => t.Legal.Contains(model.Legal));

                if (!String.IsNullOrEmpty(model.LendNO))
                    r1 = r1.Where(t => t.LendCertNO.Contains(model.LendNO));

                if (!String.IsNullOrEmpty(model.PhoneOfContactor))
                    r1 = r1.Where(t => t.ContactorPhone.Contains(model.PhoneOfContactor));

                if (!String.IsNullOrEmpty(model.PhoneOfLegal))
                    r1 = r1.Where(t => t.PhoneOfLegal.Contains(model.PhoneOfLegal));

                if (!String.IsNullOrEmpty(model.ProductNO))
                    r1 = r1.Where(t => t.ProductCertNO.Contains(model.ProductNO));

            }
            r1 = r1.OrderByDescending(t => t.Id);
            var r = r1.Select(t => (CompanyListModel)t);
            int totalCount = r.Count();
            r = r.Skip((page - 1) * PAGESIZE).Take(PAGESIZE);
            return View(new PageList<CompanyListModel>(r, page, PAGESIZE, totalCount));
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Add()
        {
            return View("Edit");
        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Add(CompanyEditModel model)
        {
            ValidateModels(model);

            if (ModelState.IsValid)
            {
                Company c = (Company)model;

                StringBuilder sb = new StringBuilder();
                foreach (var t in c.Name.ToCharArray())
                {
                    if (ChineseChar.IsValidChar(t))
                    {
                        sb.Append(new ChineseChar(t).Pinyins[0][0]);
                    }
                }
                c.PingYin = sb.ToString();

                c.CreateDT = DateTime.Now;
                c.ModifiedDT = DateTime.Now;
                c.LastModifiedUser = CurrentUserId;
                c.IsDeleted = false;
                Context.Companies.InsertOnSubmit(c);

                Context.SubmitChanges();

                Log log = new Log()
                {
                    CreateDT = DateTime.Now,
                    LastModifiedUser = CurrentUserId,
                    Type = LogTypes.Company.ToString(),
                    Value = String.Format("新增记录, {0}", c.Id),
                    RefId = c.Id,
                    OperatorType = OperatorType.Create.ToString()
                };
                Context.Logs.InsertOnSubmit(log);

                Context.SubmitChanges();
                return View("Detail", (CompanyDetailModel)c);
            }
            return View("Edit", model);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Edit(int id)
        {
            return View("Edit", (CompanyEditModel)Context.Companies.Single(t => t.Id == id));

        }

        [CookiesAuthorize]
        [HttpPost]
        public ActionResult Edit(CompanyEditModel model)
        {
            ValidateModels(model);

            if (!model.CanProduct) model.ProductNO = string.Empty;
            if (!model.CanLend) model.LendNO = string.Empty;
            if (!model.CanInstall) model.InstallNO = string.Empty;

            if (ModelState.IsValid)
            {
                var c = Context.Companies.Single(t => t.Id == model.Id);
                c.Address = model.Address;
                c.CanInstall = model.CanInstall;
                c.CanLend = model.CanLend;
                c.CanProduct = model.CanProduct;
                c.Comment = model.Comment ?? String.Empty;
                c.Contactor = model.Contactor;
                c.ContactorPhone = model.PhoneOfContactor;
                c.InstallCertNO = model.InstallNO;
                c.LastModifiedUser = CurrentUserId;
                c.Legal = model.Legal;
                c.LendCertNO = model.LendNO;
                c.ModifiedDT = DateTime.Now;
                c.PhoneOfLegal = model.PhoneOfLegal;
                c.ProductCertNO = model.ProductNO;
                Context.SubmitChanges();

                Log log = new Log()
                {
                    CreateDT = DateTime.Now,
                    LastModifiedUser = CurrentUserId,
                    Type = LogTypes.Company.ToString(),
                    Value = String.Format("修改记录, {0}", c.Id),
                    RefId = c.Id,
                    OperatorType = OperatorType.Edit.ToString()
                };
                Context.Logs.InsertOnSubmit(log);

                Context.SubmitChanges();

                return View("Detail", (CompanyDetailModel)c);

            }
            return View("Edit", model);
        }

        [CookiesAuthorize]
        public ActionResult Delete(int id)
        {
            var c = Context.Companies.Single(t => t.Id == id);
            c.IsDeleted = true;
            Context.SubmitChanges();

            Log log = new Log()
            {
                CreateDT = DateTime.Now,
                LastModifiedUser = CurrentUserId,
                Type = LogTypes.Company.ToString(),
                Value = String.Format("删除记录, {0}", c.Id),
                RefId = c.Id,
                OperatorType = OperatorType.Delete.ToString()
            };
            Context.Logs.InsertOnSubmit(log);

            Context.SubmitChanges();

            return RedirectToAction("List");

        }

        [CookiesAuthorize]
        public ActionResult Detail(int id)
        {
            var c = Context.Companies.SingleOrDefault(t => t.Id == id);
            return View("Detail", (CompanyDetailModel)c);
        }

        [CookiesAuthorize]
        [HttpGet]
        public ActionResult Search()
        {
            return View();
        }

        [CookiesAuthorize]
        public ActionResult SearchResult(CompanySearchModel model)
        {
            //var r = Context.Companies.Where(t => t.IsDeleted == false);
            //if (!string.IsNullOrEmpty(model.Name))
            //    r = r.Where(t => t.Name.Contains(model.Name));
            //r = r.OrderByDescending(t => t.Id);
            //int totalCount = r.Count();
            //var r1 = r.Select(t => (CompanyListModel)t);
            //return View("List", new PageList<CompanyListModel>(r1, 1, totalCount, totalCount));
            return RedirectToAction("List", model);
        }

        [CookiesAuthorize]
        [HttpPost]
        public ContentResult Validate(String value, String type, String Id)
        {
            bool result = true;
            int companyId = 0;
            int.TryParse(Id, out companyId);
            if (!String.IsNullOrEmpty(value))
            {
                switch (type)
                {
                    case "Name":
                        //result = Context.Companies.SingleOrDefault(t => t.Name == value && t.Id != companyId) == null;
                        result = Context.Companies.Count(t => t.Name == value && t.Id != companyId) == 0;
                        break;
                    case "ProductNO":
                        //result = Context.Companies.SingleOrDefault(t => t.ProductCertNO == value && t.Id != companyId) == null;
                        result = Context.Companies.Count(t => t.ProductCertNO == value && t.Id != companyId) == 0;
                        break;
                    case "InstallNO":
                        //result = Context.Companies.SingleOrDefault(t => t.InstallCertNO == value && t.Id != companyId) == null;
                        result = Context.Companies.Count(t => t.InstallCertNO == value && t.Id != companyId) == 0;
                        break;
                    case "LendNO":
                        //result = Context.Companies.SingleOrDefault(t => t.LendCertNO == value && t.Id != companyId) == null;
                        result = Context.Companies.Count(t => t.LendCertNO == value && t.Id != companyId) == 0;
                        break;
                    default:
                        break;
                }
            }
            return new ContentResult() { Content = result.ToString().ToLower() };
        }

        [CookiesAuthorize]
        [HttpGet]
        public JsonResult Suggestion(String type, String term)
        {
            var r = from t in Context.Companies
                    where t.IsDeleted == false
                    select t;
            switch (type)
            {
                case "owner":
                    r = r.Where(t => t.CanLend == true);
                    break;
                case "prod":
                    r = r.Where(t => t.CanProduct == true);
                    break;
                case "install":
                    r = r.Where(t => t.CanInstall == true);
                    break;
            }

            var list = r.Where(t => t.Name.Contains(term))
                .Select(t => new SuggestionModel<CompanySuggestion>()
                {
                    label = t.Name,
                    Value = t.Name,
                    Data = new CompanySuggestion()
                    {
                        Id = t.Id,
                        Legal = t.Legal,
                        Name = t.Name,
                        Phone = t.PhoneOfLegal,
                        Address = t.Address
                    }
                }).ToList();

            return new JsonResult() { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        #region  "private"
        public void ValidateModels(CompanyEditModel model)
        {
            if (model.CanInstall && String.IsNullOrEmpty(model.InstallNO))
                ModelState.AddModelError("InstallNO", "安装资质编号不能为空");

            if (model.CanLend && String.IsNullOrEmpty(model.LendNO))
                ModelState.AddModelError("LendNO", "租赁资质编号不能为空");


            if (model.CanProduct && String.IsNullOrEmpty(model.ProductNO))
                ModelState.AddModelError("ProductNO", "生产资质编号不能为空");

            if (!model.CanProduct) model.ProductNO = string.Empty;
            if (!model.CanLend) model.LendNO = string.Empty;
            if (!model.CanInstall) model.InstallNO = string.Empty;

            if (!String.IsNullOrEmpty(model.Name))
            {
                //if (Context.Companies.SingleOrDefault(t => t.Name == model.Name && t.Id != model.Id) != null)
                if (Context.Companies.Count(t => t.Name == model.Name && t.Id != model.Id) > 0)
                {
                    ModelState.AddModelError("Name", "该机构名称已存在");
                }
            }

            if (model.CanProduct)
            {
                if (Context.Companies.Count(t => t.ProductCertNO == model.ProductNO && t.Id != model.Id) > 0)
                {
                    ModelState.AddModelError("ProductNO", "该生产编号已存在");
                }
            }
            if (model.CanLend)
            {
                if (Context.Companies.Count(t => t.LendCertNO == model.LendNO && t.Id != model.Id) > 0)
                {
                    ModelState.AddModelError("LendNO", "该租赁编号已存在");
                }
            }
            if (model.CanInstall)
            {
                if (Context.Companies.Count(t => t.InstallCertNO == model.InstallNO && t.Id != model.Id) > 0)
                {
                    ModelState.AddModelError("InstallNO", "该安装编号已存在");
                }
            }

        }

        #endregion


        class CompanySuggestion
        {
            public int Id { get; set; }
            public String Name { get; set; }
            public String Legal { get; set; }
            public String Phone { get; set; }
            public String Address { get; set; }
        }
    }
}
